﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MapViewer.Loaders
{
	class FolderLoader : ILoader
	{
		#region ILoader Members

		public void Load(Action<NamedBinaryTag.TagFile> callback, Model.RecentItem source)
		{
			string[] files = System.IO.Directory.GetFiles((source as Model.FolderRecentItem).FolderPath, "map_*.dat", System.IO.SearchOption.TopDirectoryOnly);
			NamedBinaryTag.TagFile backFile = new NamedBinaryTag.TagFile();
			if (files.Length == 0)
			{
				callback(backFile);
				return;
			}
			CombineSourceBuilder builder = new CombineSourceBuilder();
			IList<NamedBinaryTag.TagFile> dataFiles = builder.LoadFiles(GetFileEnumerator(files));
			System.Windows.Rect bounds = builder.ComputeBounds(dataFiles.ToArray());
			byte[] image = builder.CreateImage(dataFiles.ToArray(), bounds);
			backFile.Init();
			backFile.RootTag.Items.Add(builder.MakeDataTag(dataFiles, image, bounds));
			callback(backFile);
		}

		#endregion

		private IEnumerator<System.IO.Stream> GetFileEnumerator(string[] files)
		{
			for (int i = 0; i < files.Length; i++)
				yield return new System.IO.FileStream(files[i], System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
		}


	}
}
